<template>
  <div class="xtx-pagination">
      {{page}}
    <a href="javascript:;" :class="{disabled:page<=1}" @click="pagechange(page-1)">上一页</a>
    <span v-if="pageInfo.pageArr[0]>1">...</span>
    <a href="javascript:;" v-for="i in pageInfo.pageArr" :key="i" 
    :class="{active:page===i}"
    @click="pagechange(i)">{{i}}</a>
    <span v-if="pageInfo.pageArr[pageInfo.pageArr.length-1]<pageInfo.totalPage">...</span>
    <a href="javascript:;" :class="{disabled:page===pageInfo.totalPage}"  @click="pagechange(page+1)">下一页</a>
  </div>
</template>
<script>
import {computed} from 'vue'
export default {
  name: 'XtxPagination',
//  接收页码等数据
  props:{
      page:{
          type:Number,
          default:1
      },
      pageSize:{
          type:Number,
          default:10
      },
      total:{
          type:Number,
          default:100
      }
  },
  setup(props,{emit}) {
    //页码切换点击
    function pagechange(num){
        // if(num<1){
        //     return
        // }
        //点击切换后的页码emit父组件
        emit('change',num)
    }
    //通过计算属性计算出总页码
    const pageInfo=computed(()=>{
        let min=props.page-2
        let max=4+min
        const totalPage=Math.ceil(props.total/props.pageSize)//通过计算属性拿到总页码
        let pageArr=[]
        //如果最小值小于
        if(min<1){
            min=1
            max=5
        }
        //最大值超过最大页码
        if(max>totalPage){
            max=totalPage
            //最小值可能小于1的情况
            min=max-4>0?max-4:1
        }
        for(let i=min;i<=max;i++){
            pageArr.push(i)
        }
        return{
            totalPage,
            pageArr
        }
    })
    return{pagechange,pageInfo}
  }
}
</script>
<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      color: @xtxColor;
    }
    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }
    &.disabled {
        //阻止鼠标点击
        pointer-events: none;
      cursor: not-allowed;
      opacity: 0.4;
      &:hover {
        color: #333
      }
    }
  }
  > span {
    margin-right: 10px;
  }
}
</style>